package com.penghk.contorller.web.resolver;

import org.apache.commons.lang.StringUtils;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.annotation.ModelAttributeMethodProcessor;

public class PageArgumentResolver extends ModelAttributeMethodProcessor {

    private int everyPage = Page.DEFAULT_EVERY_PAGE;

    public PageArgumentResolver(boolean annotationNotRequired) {
        super(annotationNotRequired);
    }

    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterType().isAssignableFrom(Page.class);
    }

    protected Object createAttribute(String attributeName, MethodParameter parameter, WebDataBinderFactory binderFactory, NativeWebRequest request) throws Exception {
        String currentPage = request.getParameter("page");

        if (StringUtils.isEmpty(currentPage)) {
            currentPage = "1";
        }

        String pageNumber = request.getParameter("pageNumber");
        if (StringUtils.isNotEmpty(pageNumber)) {
            try {
                everyPage = Integer.valueOf(pageNumber);
            }catch (Exception ignored){

            }
        }

        return new Page(Integer.valueOf(currentPage), everyPage);
    }
}
